<?php
use think\Session;
use think\Db;
use think\Config;
require_once (APP_PATH . 'api/FinanceApi.php');
/**
 * @description  	奖励接口
 * @author      	褚天恩 <chutianen@163.com>
 * @date 2018-03-18 时间
 * @version 1.0.0	版本
 * 
 * 奖金制度
	
 * 
 * 
 * 
 * @copyright
 */
class RewardApi {
	/**
	 * 构造函数
	 */
	function __construct(){
		
	}
	/**
	 * 入口文件（奖励）
	 * @param 用户id  $member_id
	 * @param 消费金额    $money
	 * @param 分区	 $type
	 * @param 商品id  $goods_id
	 * @param 订单序列号 $orders_id
	 * @return string
	 */
	public function begin($member_id,$num,$user,$type){
		
		//先给会员加个人业绩和团队业绩
		$r['member'] = $this->updateMemberBuyNum($member_id,$num);
		
		$member = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		//配置项信息
		$r['config'] = $this->updateConfigFenHong($num,$member['level']);
		if($type == 1){
			//直推奖
			$r['zhitui'] = $this->zhitui($member, $num,$user);
		}
 		//合伙人培养奖
 		$r['peiyang'] = $this->peiyang($member,$num,$user);
 		//合伙人团队业绩每满足1000的奖励
// 		$r['hehuo'] = $this->hehuo($member,$num);

		return $r;
	}
	/**
	 * 修改用户购买数量
	 * 并且判断用户是否升级
	 */
	public function updateMemberBuyNum($member_id,$num){
		$reward = new \RewardApi();
		$up_list = $reward->getUpUserByTuiJianId($member_id, 999);
		$member =  Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		//修改个人业绩
		$list_member['yeji_self'] = $member['yeji_self'] + $num;
		$res['yeji_self'] = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->update($list_member);
		foreach($up_list as $k=>$v){
			if($up_list[$k]){
				$up_data['yeji'] = $up_list[$k]['yeji'] + $num;
				if($v['level']==3){
                    $up_data['hhr_yeji'] = $up_list[$k]['hhr_yeji'] + $num;  //添加合伙人团队业绩
                }
				$res['yeji_team'] = Db::name('App_member_relation')->where(array('member_id'=>$up_list[$k]['member_id']))->update($up_data);
			}

		}
		//判断升级
		if($member['level'] == 2){
			//判断降级时间戳之后的个人业绩
			$where['status'] = 2;
			$where['add_time'] = array('egt',$member['jtime']);
			$where['member_id'] = $member_id;
			$yj_num =  Db::name('orders')->where($where)->sum('num');
			if($yj_num>=2000 ){   //如果个人业绩大于等于2000
				$st['level'] = 3;
				$res[] = Db::name('app_member_relation')->where('member_id',$member_id)->update($st);
			}
		}
		foreach($up_list as $k=>$v){
            //合伙人团队业绩每满足1000的奖励
            $this->hehuo($v);
        }
		return $res;
	}
	/**
	 * 修改配置当中的全球分红金额
	 * @param unknown $price
	 */
	public function updateConfigFenHong($num,$level){
		//配置项信息
		$config = $this->configs();
		$arr['sell_num_all'] = $num + $config['sell_num_all'];  
		$arr['sell_num_'.$level] = $num + $config['sell_num_'.$level];
		//修改配置项信息
		foreach ($arr as $k => $v){
			$config_data['value'] = $v;
			$res = Db::name('App_config')->where('key',$k)->update($config_data);
		}
		return $res;
	}
	
	
	
	
	/**
	 * 平级奖励			OK
	 * @param unknown $userId
	 * @param unknown $jifen
	 */
	public function zhitui($member,$num,$user){
		
		$zhuce = Db::name('App_member_relation')->where(array('member_id'=>$member['zhuceid']))->find();
		//没有推荐人
		if(empty($zhuce)){
			return true;
		}
		//判断当前用户与推荐人等级是否相等
		if($member['level'] != $zhuce['level']){
			return true;
		}
		//推荐人的等级
		$class = $this->getLevel($zhuce['level']);
		//推荐人获得奖励
		$jiangli = $num * $class['pingji_money'];
		$res[] = $this->addUserMoney($zhuce['member_id'], $jiangli, 1,'来自'.$user['loginName']);
		return $res;
	}
	/**
	 * 培养奖励
	 * @param unknown $member_id
	 * @param unknown $num
	 */
	public function peiyang($member,$num,$user){
		//判断自己是不是
		if($member['level'] != 3){
			return true;
		}
		$num += $member['bili_yeji'];   //查看培养奖的剩余数量
        $bl = 0;    //本次订单可奖励的倍数
        for($i=0;$i<99;$i++){
            if($num>=100){
                $num = $num-100;
                $bl++;
            }else{
                break;
            }
        }
        $member['bili_yeji'] = $num;    //将剩余业绩保存
        Db::name('App_member_relation')->update($member);
        if($bl==0){
            return true;    //如果一次都不满100支   直接退出
        }
		//差上3代 
		$up_list = $this->getUpUserByTuiJianId($member['member_id'], 99);
		$list = array_reverse($up_list);
		$level = Db::name('App_level')->where('id',$member['level'])->find();
		$bili = explode(':',$level['dongtai_bili']);   //获取三级奖金比例
        $lv[3] = $bili[0] * 100 * $bl;  //奖金额
        $lv[2] = $bili[1] * 100 * $bl;
        $lv[1] = $bili[2] * 100 * $bl;
        $finance = new \FinanceApi();
        $cou = 1;
        foreach($list as $k=>$v){
            if($v['member_id']==$member['member_id']){    //0为自己   直接跳过
                continue;
            }
            if($cou<=3){
                if($v['level']==3){
                    $this->addUserMoney($list[$k]['member_id'],$lv[$cou],2,'来自'.$user['loginName']);
                    $cou++;
                }
            }
        }



//        if($one_num>=4){    //如果能查到向上三级
//            if($list[0]['level'] == 3 && $list[1]['level'] == 3 && $list[2]['level'] == 3){
//                //a有奖励
//                $this->addUserMoney($list[2]['member_id'],$lv1,2);
//                $this->addUserMoney($list[1]['member_id'],$lv2,2);
//                $this->addUserMoney($list[0]['member_id'],$lv3,2);
//            }else if( $list[1]['level'] == 3 && $list[2]['level'] == 3 && $list[4]['level'] == 3){
//                //b有奖励
//                $this->addUserMoney($list[2]['member_id'],$lv1,2);
//                $this->addUserMoney($list[1]['member_id'],$lv2,2);
//            }else if($list[2]['level'] == 3 && $list[4]['level'] == 3 && $list[5]['level'] == 3){
//                //c有奖励
//                $this->addUserMoney($list[2]['member_id'],$lv1,2);
//            }
//        }else if($one_num==3){    //如果向上少于三级
//            if($list[0]['level'] == 3 && $list[1]['level'] == 3 && $list[3]['level'] == 3){
//                //a有奖励
//                $this->addUserMoney($list[0]['member_id'],$lv1,2);
//                $this->addUserMoney($list[1]['member_id'],$lv2,2);
//            }else if( $list[1]['level'] == 3 && $list[3]['level'] == 3 && $list[4]['level'] == 3){
//                //b有奖励
//                $this->addUserMoney($list[1]['member_id'],$lv1,2);
//            }
//        }else if($one_num==2){
//            if($list[0]['level'] == 3 && $list[2]['level'] == 3 && $list[3]['level'] == 3){
//                $this->addUserMoney($list[0]['member_id'],$lv1,2);
//            }
//        }

		return true;
		
		
		
		
		
	}
	
	/**
	 * 合伙人团队业绩每满1000支返钱
     * $member   当前会员的信息
	 */
	public function hehuo($member){
		
		//如果用户身份为合伙人  则累计进货数量   满2000返利
		$member = Db::name('App_member_relation')->where('member_id',$member['member_id'])->find();
		$finance = new \FinanceApi();
		if($member['level'] == 3){
            $config = Db::name('app_config')->where('key','hhr_jj')->find();
            $reward = $config['value'] * 1000;     //本次奖金
		    for($i=0;$i<=99;$i++){
                $n = $member['hhr_yeji']-$member['reward_num']*1000;
                if($n>=1000){
                    $member['reward_num']++;    //自身奖励数量增加
                    $act = Db::name('app_member_account')->where('member_id',$member['member_id'])->find();    //获取用户钱包
                    $act['account_type_1']+=$reward;     //增加奖励
                    Db::name('app_member_account')->where('member_id',$member['member_id'])->update($act);   //更新钱包
                    $finance->addFinance($member['member_id'],4,'合伙人返利',1,$reward,1);  //添加日志
                }else{
                    break;
                }
            }
            Db::name('App_member_relation')->update($member);

//			$hhr_yeji = $member['hhr_yeji'] + $num;
//			if($hhr_yeji>=2000){
//				$dj = Db::name('app_config')->where('key','hhr_jj')->find();
//				$all_jj = $dj['value'] * 2000;
//				$vl['hhr_yeji'] = $hhr_yeji - 2000;
//				$act = Db::name('app_member_account')->where('member_id',$member['member_id'])->find();
//				$act['account_type_1']+=$all_jj;
//				Db::name('app_member_account')->where('member_id',$member['member_id'])->update($act);   //更新钱包
//				$finance->addFinance($member['member_id'],4,'合伙人返利',1,$all_jj,1);  //添加日志
//			}else{
//				$vl['hhr_yeji'] = $hhr_yeji;
//			}
//			Db::name('app_member_relation')->where('member_id',$member['member_id'])->update($vl);    //扣除奖励数量的更新
            return true;
		}
		
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 无限代层碰对碰奖				
	 * @param 被激活会员     $user
	 * @param 激活金额        $money
	 * @return unknown
	 * （三点取最小值，例如：A为5000的银卡会员，他的左区会员为10000的金卡会员，右区为10000的红钻会员，他的第一层层碰为5000的50%2500元。）
	 */
	public function addCengPengYeJi($member_id,$money){
		$member = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		$list = $this->getUpUserByjiedianId($member_id,9999);
		for($i=1;$i<count($list);$i++){
			//加左右区业绩
			if($list[$i-1]['quyu'] == 'righ'){
				//给第i层加
				$where['member_id'] = $list[$i]['member_id'];
				$where['layer'] = $i;
				$layer = Db::name('App_layer')->where($where)->find();
				if($layer){
					$res = Db::name('App_layer')->where($where)->setInc('righ_yeji',$money);
				}else{
					$data['member_id'] = $list[$i]['member_id'];
					$data['layer'] = $i;
					$data['left_yeji'] = 0;
					$data['righ_yeji'] = $money;
					$res =Db::name('App_layer')->add($data);
				}
				
				$quyu = 'righ';
				
			}else{
				$where['member_id'] = $list[$i]['member_id'];
				$where['layer'] = $i;
				$layer = Db::name('App_layer')->where($where)->find();
				if($layer){
					$res = Db::name('App_layer')->where($where)->setInc('left_yeji',$money);
				}else{
					$data['member_id'] = $list[$i]['member_id'];
					$data['layer'] = $i;
					$data['left_yeji'] = $money;
					$data['righ_yeji'] = 0;
					$res = Db::name('App_layer')->add($data);
				}
				$quyu = 'left';
				
			}
			//如果是股东没有奖励
			if($list[$i]['level'] == 5){
				return true;
			}
			$map['member_id'] = $list[$i]['member_id'];
			$map['layer'] = $i;
			$member_layer = Db::name('App_layer')->where($map)->find();
			// 			dump($member_layer);
			
			$class = $this->getLevel($list[$i]['level']);

			if($member_layer['left_yeji']>0 && $member_layer['righ_yeji']>0){
				//比例
				if($i == 1){
					$bili = $class['cengpeng_bili_1']/100;
				}else{
					$bili = $class['cengpeng_bili_2']/100;
				}
				if($member_layer['whether'] != 0){
					
					if($quyu == 'left'){
						$contrast = $list[$i]['righ_surplus'];
					}else{
						$contrast = $list[$i]['left_surplus'];
					}
					$yeji=min($contrast,$money);
					//量碰
					$this->tuiguang($yeji,$list[$i],$member);
					//减少当前用户左右剩余业绩
					//对碰之后开始减钱
					Db::name('App_member_relation')->where(array('member_id'=>$list[$i]['member_id']))->setDec("left_surplus",$yeji);
					Db::name('App_member_relation')->where(array('member_id'=>$list[$i]['member_id']))->setDec("righ_surplus",$yeji);
				}else{
					//左区业绩  右区业绩和自身机会金额求最小
					$yeji = $this->minimum($member_layer['left_yeji'],$member_layer['righ_yeji'],$class['money']);
					//层碰
					$money_jiangjin=$yeji*$bili;
					
					if ($money_jiangjin>0){
						//加钱假日志操作
						$status = $this->addUserMoney($list[$i]['member_id'],$money_jiangjin,2);
						
						$whether['whether'] = 1;
						Db::name('App_layer')->where($map)->save($whether);
					}
					//对碰之后开始减钱
					Db::name('App_layer')->where($map)->setDec("left_yeji",$yeji);
					Db::name('App_layer')->where($map)->setDec("righ_yeji",$yeji);
				}
			}
		}
		return $status;
	}
	/**
	 * 获得左右剩余业绩
	 */
	public function getShengYuYeJi($member_id){
		$layer = Db::name('App_layer')->where(array('member_id'=>$member_id))->select();
		foreach($layer as $k=>$v){
			$left_yeji += $layer[$k]['left_yeji'];
			$righ_yeji += $layer[$k]['righ_yeji'];
			
		}
		
		
	} 
	
	
	
	/**
	 * 三个数求最小
	 * @param unknown $a
	 * @param unknown $b
	 * @param unknown $c
	 */
	public function minimum($a,$b,$c){
		$min = $a<$b?($a<$c?$a:$c):($b<$c?$b:$c);
		return $min;
	}
	
	/**
	 * 量奖				OK
	 * @param unknown $money
	 * @return unknown
	 * （日封顶，封顶金额为投资额  银卡10000元，金卡20000元。）小区新增业绩的10%。例：参与层碰后不算新增业绩。
	 */
	public function tuiguang($money,$member,$user){
		$class = $this->getLevel($member['level']);
		//产生互助奖
		$bili = $class['liangpeng_bili']/100;
		$jiangjin = $money*$bili;
		$r[] = $this->addUserMoney($member['member_id'], $jiangjin, 3);
		//触发管理奖
		$r[] = $this->guanli($member['member_id'], $jiangjin);
		return $r;
	}
	/**
	 * 管理奖
	 * @param unknown $member_id
	 * @param unknown $money
	 */
	public function guanli($member_id,$money){
		//查询上下各5代的推荐关系
		$up_list = $this->getUpUserByTuiJianId($member_id, 5);
		$down_list = $this->getdown($member_id, 3);
		for($i = 1;$i<count($up_list);$i++){
			//如果是股东没用管理奖
			if(!empty($up_list[$i]) && $up_list[$i]['level'] != 5){
				$class_up = $this->getLevel($up_list[$i]['level']);
				//判断当前用户的管理奖向下代数
				if($class_up['guanli_daishu_down'] >= $i){
					//能拿到管理奖
					$bili_up = $class_up['guanli_bili']/100;
					$jiangli = $money*$bili_up;
					$up_r[] = $this->addUserMoney($up_list[$i]['member_id'], $jiangli, 4);
					
				}
			}
		}
		
		//下级三代的所有用户组成的数组
		foreach($down_list as $k=>$v){
			//如果是股东没用管理奖
			if(!empty($down_list[$k]) && $down_list[$k]['level'] != 5){
				$class_down = $this->getLevel($down_list[$k]['level']);
				//如果当前用户的管理奖向上代数大于他所在的层数的时候有管理奖
				if($class_down['guanli_daishu_up'] >= $down_list[$k]['ceng']){
					//能拿到管理奖
					$bili_down = $class_down['guanli_bili']/100;
					$all_jiangli = $money*$bili_down;
					$jiangli = $all_jiangli/$down_list[$k]['count'];
					$down_r[] = $this->addUserMoney($down_list[$k]['member_id'], $jiangli, 4);
				}
			}
		}
		if($down_r || $up_r){
			return true;
		}else{
			return false;	
		}
	}
	/**
	 * 股东分红奖
	 */
	public function gudong($new_yeji){
		$where['status'] = 1;
		$where['level'] = 5;
		//当前所有的股东的数量
		$count = Db::name('App_member_relation')->where($where)->count();
		//总分红份数 = 股东数 × 10份 ➕ 推荐股东奖励分红份数总额
		$all_fen_num = $count*11;
		//每份分红金额 = 每月新增业绩 × 5% /总分红份数    这个是推荐股东的会员单独获得的  1份的金额
		$config = $this->configs();
		$bili = $config['gudong_fenhong_bili']/100;
		$one_fen_money = $new_yeji * 0.05 / $all_fen_num;
		//股东获得的加权分红金额
		$gudong_money = $one_fen_money * 10;
		//每份的分红
		if(empty($one_fen_money)){
			return true;
		}
		//全部股东的信息
		$all_gudong = Db::name('App_member_relation')->field('member_id,status,is_release_gd,zhuceid,level')->where($where)->select();
		foreach($all_gudong as $k=>$v){
			//如果股东的释放股东分红状态为1  并且本身账号状态值为1  释放股东分红
			if($all_gudong[$k]['is_release_gd'] == 1 && $all_gudong[$k]['status'] == 1){
				$r[] = $this->addUserMoney($all_gudong[$k]['member_id'], $gudong_money, 5);
			}	
			//所有股东对应的推荐人的id
			$zhuceid_arr[] = $all_gudong[$k]['zhuceid']; 
		}
		$where_zhuce['member_id'] = array('in',$zhuceid_arr);
		//查询所有股东对应推荐人信息
		$all_zhuce = Db::name('App_member_relation')->field('member_id,status,is_release_tj')->where($where_zhuce)->select();
		foreach($all_zhuce as $m=>$n){
			//如果当前的股东推荐人的推荐分红开关为1   并且自身的状态值为1  
			if($all_zhuce[$m]['is_release_tj'] == 1 && $all_zhuce[$m]['status'] == 1){
				$r[] = $this->fenhongaddUserMoney($all_zhuce[$m]['member_id'], $one_fen_money, 8);
			}
		}
		//修改当月的新增业绩
		$rs = Db::name('app_config')->where("wst_app_config.key='now_new_yeji'")->setField('value',0);
		return $r;
	}
	/**
	 * 激励分红
	 * 前100名股东与钻卡，享有每月新增业绩5%的加权分红。
	 * 这个是前100名内的股东除了股东分红外的另一个分红。
	 */
	public function jili($new_yeji){
		if(!$new_yeji){
			return false;
		}
		$arr_level[] = 4;
		$arr_level[] = 5; 
		$where['level'] = array('in',$arr_level);
		$where['status'] = 1;
		//当前所有的股东的数量
		$count = Db::name('App_member_relation')->where($where)->count();
		//每份分红金额 = 每月新增业绩 × 5% /总分红份数    这个是推荐股东的会员单独获得的  1份的金额
		$config = $this->configs();
		$bili = $config['jili_fenhong_bili']/100;
		$gudong_money = $new_yeji * $bili / $count;
		//每份的分红
		if(empty($gudong_money)){
			return true;
		}
		//全部股东的信息
		$all_gudong =  Db::name('App_member_relation')->field('member_id,is_release_jl,level,status')
														  ->where($where)
														  ->limit(100)->order('member_id')
														  ->select();
		foreach($all_gudong as $k=>$v){
			//如果股东的释放 激励分红 状态为1  并且本身账号状态值为1   激励分红
			if($all_gudong[$k]['is_release_jl'] == 1 && $all_gudong[$k]['status'] == 1){
				$r[] = $this->fenhongaddUserMoney($all_gudong[$k]['member_id'], $gudong_money, 6);
			}
		}
		//修改当月的新增业绩
		$rs = Db::name('app_config')->where("wst_app_config.key='now_new_jili_yeji'")->setField('value',0);
		return $r;
	}
	
	
	
	
	/**
	 * 为上线增长业绩
	 * @param 入金的会员信息 $user
	 * @param 入金金额 $money
	 */
	 
	public function addYeJi($member_id,$money){
		$list = $this->getUpUserByjiedianId($member_id,9999);
		for($i=1;$i<count($list);$i++){
			if($list[$i-1]['quyu'] == 'righ'){
				$data['yeji_righ'] = $list[$i]['yeji_righ']+$money;
				$data['righ_surplus'] = $list[$i]['righ_surplus']+$money;
			}else{
				$data['yeji_left'] = $list[$i]['yeji_left']+$money;
				$data['left_surplus'] = $list[$i]['left_surplus']+$money;
			}
			//为上线加业绩
			$data['yeji'] = $list[$i]['yeji']+$money;
			//为上线加团队人数
			$data['tream_num'] = $list[$i]['tream_num']+1;
			$res[] = M('App_member_relation')->where('member_id='.$list[$i]['member_id'])->update($data);
			unset($data);
		}
		return $res;
	}
	
	
	/**
	 * 报单中心奖
	 * 注册激活为报单中心每单固定奖励
	 */
	public function baodan($member_id,$money){
		$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		$member_relation_baodan = Db::name('App_member_relation')->where(array('member_id'=>$member_relation['baodan']))->find();
		$class = $this->getLevel($member_relation_baodan['level']);
		if($member_relation_baodan){
			$jiangli = $class['baodan'];
			if($jiangli > 0){
				$r = $this->addUserMoney($member_relation_baodan['member_id'],$jiangli,7);
			}
		}
		return $r;
	}
	/**
	 * 修改当月的新增业绩
	 * @param unknown $money
	 * @return unknown
	 */
	public function addNewYeji($money){
		$config = $this->configs();
		$now_new_jili_yeji = $config['now_new_jili_yeji'];
		$now_new_yeji = $config['now_new_yeji'];
		$data['now_new_jili_yeji'] = $now_new_jili_yeji + $money;
		$data['now_new_yeji'] = $now_new_yeji + $money;
		//其他配置想修改
		foreach ($data as $k=>$v){
			$rs[] = Db::name('app_config')->where("wst_app_config.key='{$k}'")->setField('value',$v);
		}
		return $rs;
	}
	
	
	
	
	/**
	 * 判断每日奖励上限
	 * @param unknown $member_id
	 */
	public function judge($member_id,$jiangli){
		$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		$class = $this->getLevel($member_relation['level']);
		
		//判断每天互助将上线
		$time = $this->toDayTime();
		$aa[] = $time['start'];
		$aa[] = $time['end'];
		$where['member_id'] = $member_id;
		$type[] = 6;
		$type[] = 7;
		$type[] = 8;
		$type[] = 9;
		$type[] = 10;
		$type[] = 11;
		$type[] = 12;
		$type[] = 13;
		$type[] = 14;
		$where['finance_type'] = array('in',$type);
		$where['add_time'] = array('between',$aa);
		$sum_money = Db::name('App_finance')->where($where)->sum('money');
		$all_money = $sum_money + $jiangli;
		
		if($all_money > $class['money']){
			//超出上线了
			$return['money'] = $class['money'] - $sum_money;
			//超出
			$return['type'] = 1;
		}else if($all_money == $class['money']){
			//超出上线了
			$return['money'] = $jiangli;
			//超出
			$return['type'] = 0;
		}else{
			//正常释放
			$return['money'] = $jiangli;
			//超出
			$return['type'] = 0;
		}
		return $return;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	/**
	 * 今日零点到24点时间段
	 * 数组形式返回
	 */
	public function toDayTime(){
		$time['start'] = strtotime(date('Y-m-d',time()));
		$time['end'] = $time['start']+84600;
		return $time;
	}
	
	
	
	/**
	 * 通过节点关系查找
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getPidById($id,$k=0){
		$area = Db::name("Areas")->where(array('areaId'=>$id))->find();
		$k++;   
		if (!empty($area)) {
			$item[]=$area;
			if ($k < 3) {
				$list = $this->getPidById($area['parentId'],$k);
				for($i = 0;$i<count($list);$i++){
					if(!empty($list[$i])){
						$item[] = $list[$i];
					}
				}
			}
		}
		return $item;
	}
	/**
	 * 给用户钱包加钱
	 * @param unknown $userId
	 * @param unknown $money
	 */
	public function addUserMoney($member_id,$money,$type,$content_two){
		if($money <= 0){
			return true;
		}
		//根据类型获得对应参数
		$arr = $this->getArrByType($type);
		//分配奖励
		$money_arr = $this->fenpei($money);
		$jiang_arr = $money_arr['jiang'];
		$fee = $money_arr['fee'];
		//实例化日志api
		$finance = new \FinanceApi();
		foreach($jiang_arr as $k=>$v){
			if($jiang_arr[$k]['money'] >=0){
				$content = $arr['content'].'-'.$jiang_arr[$k]['name'];
				
				//发放奖励
				$r[] = Db::name('App_member_account')->where(array('member_id'=>$member_id))->setInc('account_type_'.$jiang_arr[$k]['type'],$jiang_arr[$k]['money']);
				//添加日志
				$r[] = $finance->addFinance($member_id,$arr['finance_type'],$content.$content_two,1,$jiang_arr[$k]['money'],$jiang_arr[$k]['type']);	
			}
		}
		if($fee['money']){
			$r[] = $finance->addFinance($member_id,6,$arr['content'].'，手续费'.$fee['money'],2,$fee['money'],'');
		}
		return $r;
	}           

	/**
	 * 给用户钱包加钱
	 * @param unknown $userId
	 * @param unknown $money
	 */
	public function fenhongaddUserMoney($member_id,$money,$type){
		if($money <= 0){
			return true;
		}
		//根据类型获得对应参数
		$arr = $this->getArrByType($type);
		//分配奖励
		$money_arr = $this->fenpei($money);
		$jiang_arr = $money_arr['jiang'];
		$fee = $money_arr['fee'];
		//实例化日志api
		$finance = new \FinanceApi();
		foreach($jiang_arr as $k=>$v){
			if($jiang_arr[$k]['money'] >=0){
				$content = $arr['content'].'-'.$jiang_arr[$k]['name'];
				//发放奖励
				$r[] = Db::name('App_member_account')->where(array('member_id'=>$member_id))->setInc('account_type_'.$jiang_arr[$k]['type'],$jiang_arr[$k]['money']);
				//添加日志
				$r[] = $finance->addFinance($member_id,$arr['finance_type'],$content,1,$jiang_arr[$k]['money'],$jiang_arr[$k]['type']);
				// 				$r[] = $finance->addFinance($member_id, $finance_type, $content, $money_type, $money, $account_type)
			}
		}
		if($fee['money']){
			$r[] = $finance->addFinance($member_id,6,$arr['content'].'，综合管理费'.$fee['money'],2,$fee['money'],'');
		}
		return $r;
	}
	
	
	
	/**
	 * 奖励分配
	 * @param unknown $money
	 * @return number
	 */
	public function fenpei($money){
		$config = $this->configs();
		//手续费比例
		$fee_bili = $config['fee'] /100;
		$arr['jiang'][0]['name'] = '奖金';
		$arr['jiang'][0]['money'] = (1 - $fee_bili) * $money;
		$arr['jiang'][0]['type'] = '1';
		$arr['fee']['money'] = $fee_bili * $money;
		return $arr;
	}
	/**
	 * 配置项信息
	 * @return multitype:
	 */
	public function configApp(){
		//获取配置信息
		$config = DB::name('App_config')->select();
		foreach($config as $k=>$v){
			$list[$v['key']]=$v['value'];
		}
		return $list;
	}
	/**
	 * 获得奖励内容
	 * @param unknown $type
	 * @return string
	 */
	public function getArrByType($type){
		switch ($type){
			case 1:
				$arr['content'] = '平级分红奖励';
				$arr['finance_type'] = 3;
				break;
			case 2:
				$arr['content'] = '合伙人培养奖励';
				$arr['finance_type'] = 13;
				break;
			case 3:
				$arr['content'] = '量奖';
				$arr['finance_type'] = 9;
				break;
			case 4:
				$arr['content'] = '管理奖';
				$arr['finance_type'] = 10;
				break;
			case 5:
				$arr['content'] = '股东分红';
				$arr['finance_type'] = 11;
				break;
			
		}
		return $arr;
	}
	/**
	 * 递归查找上级推荐会员
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getUpUserByTuiJianId($id,$lv,$k=0){
		$member_relation = Db::name("App_member_relation")->where(array('member_id'=>$id))->find();
//		dump($member_relation);die;
//		return $member_relation;
		$k++;
		if (!empty($member_relation)) {
			$item[]=$member_relation;
			if ($k<$lv) {
				$list = $this->getUpUserByTuiJianId($member_relation['zhuceid'],$lv,$k);
				for($i = 0;$i<count($list);$i++){
					if(!empty($list[$i])){
						$item[] = $list[$i];
					}
				}
			}
		}
		return $item;
	}
	/**
	 * 递归查找上级节点会员
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getUpUserByjiedianId($id,$lv,$k=0){
		$member_relation = Db::name("App_member_relation")->where(array('member_id'=>$id))->find();
		$k++;
		if (!empty($member_relation)) {
			$item[]=$member_relation;
			if ($k<$lv) {
				$list = $this->getUpUserByjiedianId($member_relation['jiedianid'],$lv,$k);
				for($i = 0;$i<count($list);$i++){
					if(!empty($list[$i])){
						$item[] = $list[$i];
					}
				}
			}
		}
		return $item;
	}
	/**
	 * 递归查找下级推荐会员
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getDownUserByTuiJianId($id,$lv,$k=0){
		$member_relation = Db::name("App_member_relation")->where(array('member_id'=>$id))->find();
		$k++;
		if (!empty($member_relation)) {
			$item[]=$member_relation;
			if ($k<$lv) {
				$list = $this->getUpUserByTuiJianId($member_relation['zhuceid'],$lv,$k);
				for($i = 0;$i<count($list);$i++){
					if(!empty($list[$i])){
						$item[] = $list[$i];
					}
				}
			}
		}
		return $item;
	}
	/**
	 * 通过节点关系查找
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getdown($member_id,$lv,$k=0){
		$down_one = Db::name('App_member_relation')->field('member_id,level')->where(array('zhuceid'=>$member_id))->select();
		if (!empty($down_one)) {
			foreach($down_one as $k=>$v){
				$down_one[$k]['ceng'] = 1;
				$down_one[$k]['count'] = count($down_one);
				$down_two[] = $this->getNowDownMember($down_one[$k]['member_id']);
			}
		}
		//整合所有第二层的用户
		$down_two = $this->hebinArr($down_two,2);
		if(!empty($down_two)){
			foreach($down_two as $m=>$n){
				
				$down_two[$m]['count'] = count($down_two);
				$down_three[] = $this->getNowDownMember($down_two[$m]['member_id']);
			}
			//整合所有第三层的用户
			$down_three = $this->hebinArr($down_three,3);
			if(!empty($down_three)){
				foreach($down_three as $p=>$q){
					$down_three[$p]['count'] = count($down_three);
				}
				$two_three = array_merge($down_two,$down_three);
			}else{
				$two_three = $down_two;
			}
		}
		//将第一层第二层第三层的用户河滨在一起
		if(!empty($two_three)){
			$item = array_merge($down_one,$two_three);
		}else{
			$item = $down_one;
		}
		return $item;
	}
	public function getNowDownMember($member_id){
		$down_member = Db::name('App_member_relation')->field('member_id,level')->where(array('zhuceid'=>$member_id))->select();
		return $down_member;
	}
	/**
	 * 整合当前的用户  从三维数组变成二位数组
	 * @param unknown $arr
	 * @return unknown
	 */
	public function hebinArr($arr,$ceng){
		$array = array();
		if(!empty($arr)){
			foreach($arr as $k=>$v){
				if(!empty($arr[$k])){
					foreach($arr[$k] as $m=>$n){
						//写入数组  第几层的用户
						$arr[$k][$m]['ceng'] = $ceng;
						$array[] = $arr[$k][$m];
					}
				}
			}
		}
		return $array;
	}
	/**
	 * 判断会员等级
	 * @param unknown $level
	 */
	public function getLevel($level){
		$class = Db::name('App_level')->where(array('id'=>$level))->find();
		return $class;
	}
	//查询配置
	public function configs(){
		$list = Db::name('App_config')->select();
		foreach($list as $key=>$value){
			$list[$value['key']] = $value['value'];
		}
		return $list;
	}
    //查询会员等级 查询分红钱数 判断购买商品时分红
    public function jiangjin($member,$num,$sid){
        //购买商品时返利
        $res = Db::table('wst_app_member_relation')
            ->alias('a')
            ->field('a.zhuceid,b.name,b.member_num')
            ->join('wst_app_level b','a.level = b.id')
            ->where('a.member_id',$member['member_id'])
            ->find();

        //查询用户钱包金额
        $yue = Db::name('App_member_account')->where('member_id',$res['zhuceid'])->field('account_type_1')->find();
        //查询购买的商品数量
        $nums = Db::table('wst_orders')
            ->alias('a')
            ->field('b.inventory')
            ->join('wst_goods b','a.gid = b.id')
            ->where('a.member_id',$member['member_id'])
            ->find();

        if (!empty($res['zhuceid']))
        {
            $money['member_id'] = $res['zhuceid'];
            $money['content'] = '平级分红';
            $money['money'] = $res['member_num'] * $nums['inventory'];
            $money['balance'] = $yue['account_type_1'];
            $money['add_time'] = $_SERVER['REQUEST_TIME'];
            $money['finance_type'] = 3;
            $money['money_type'] = 1;
            $money['account_type'] = 1;
            $money['sid'] = $sid;
//            dump($money);exit;
            $finance = new  \FinanceApi();
            $tianjia = $finance->addFinance($money['member_id'],$money['finance_type'],$money['content'],$money['money_type'],$money['money'],$money['account_type'],$member['member_id']);
//            $list = Db::name('App_finance')->insert($money);
            $qian['account_type_1'] = $yue['account_type_1'] + $res['member_num'];
            Db::name('App_member_account')->where('member_id',$res['zhuceid'])->update($qian);
        }
        return $tianjia;
    }
//    //查询晋升合伙人之后 下面是否有三个合伙人如果有5:3:3分红
//    public function hehuo($member)
//    {
//        $aa = Db::name('App_member_relation')->where('zhuceid',$member['member_id'])->select();
////        dump($aa);
//    }
    public function counts($member,$level)
    {

        $list = Db::name('app_member_relation')
            ->where('zhuceid',$member['member_id'])
            ->where('level = 2')
            ->select();

//        dump($list);exit;
//            foreach ($list as $key => $value)
//            {
//                $level++;
////                $arr[]
//            }
////        return 1;
//        return $level;
        return $list;
    }
}
